package com.recource.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.recource.annonation.Login;
import com.recource.domain.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.recource.dao.*;
import com.recource.ro.PageRO;
import com.recource.util.HostHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.nio.charset.StandardCharsets;
import java.util.*;

@Controller
@RequestMapping("/admin")
@Transactional(rollbackFor = Exception.class)
@Login
public class AdminController {

    @Autowired
    private UserDao userDao;

    @Autowired
    private FileDao fileDao;

    @Autowired
    private TypeDao typeDao;

    @Value("${file.root}")
    private String root;

    @Value("${system.previewUrl}")
    private String url;
    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private ApplicationDao applicationDao;


    @RequestMapping("/index")
    public String index(){
        return "redirect:/admin/config/page";
    }

    @RequestMapping("/user/add.html")
    public String addHtml(){
        return "/admin/user/detail";
    }

    //用户列表分页接口
    @RequestMapping("/user/page")
    public ModelAndView list(PageRO<Users> ro){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/admin/user/list");
        //查找是否请求参数中有搜索值
        //分页查询用户
        if(StringUtils.isEmpty(ro.getSex())){
            ro.setSex(null);
        }
        if(StringUtils.isEmpty(ro.getUsername())){
            ro.setUsername(null);
        }
        Page<Users> page = userDao.selectPageBySearch(ro);
        //将结果注入页面返回
        modelAndView.addObject("page", page);
        return modelAndView;
    }

    //用户详情接口
    @RequestMapping("/user/detail")
    public ModelAndView detail(String id){
        ModelAndView modelAndView = new ModelAndView();
        LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<>();
        //where条件搜索是否有符合条件的id用户
        wrapper.eq(Users::getId, id);
        Users users = userDao.selectOne(wrapper);
        //如果用户不存在就报错
        if(users == null){
            throw new RuntimeException("用户不存在");
        }
        //跳转页面
        modelAndView.setViewName("/admin/user/detail");
        //将用户信息注入视图层
        modelAndView.addObject("user", users);
        return modelAndView;
    }

    //更新和新增用户层
    @RequestMapping("/user/update")
    public ModelAndView update(Users ro){
        ModelAndView modelAndView = new ModelAndView();
        LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<>();
        if(Objects.nonNull(ro.getId())){
            wrapper.eq(Users::getId, ro.getId());
            //用户id作为查询条件搜索用户
            Users users = userDao.selectOne(wrapper);
            if(users == null){
                throw new RuntimeException("用户不存在");
            }
            //将更新内容更新到新属性
            users.setUsername(ro.getUsername());
            users.setUserType(ro.getUserType());
            users.setPhone(ro.getPhone());
            users.setIdCard(ro.getIdCard());
            users.setPerfession(ro.getPerfession());
            //
            users.setSex(ro.getSex());
            users.setDate(ro.getDate());
            users.setAddress(ro.getAddress());
            users.setEmail(ro.getEmail());
            //在数据库中更新用户
            userDao.updateById(users);
        }else{
            //新增用户
            //查看用户名是否存在
            wrapper.eq(Users::getUsername, ro.getUsername());
            Users users = userDao.selectOne(wrapper);
            if(users != null){
                throw new RuntimeException("用户名已经存在了");
            }
            //注入用户的相关信息
            Users newuser = new Users();
            String salt = UUID.randomUUID().toString().substring(0, 5);
            newuser.setSalt(salt);
            StringBuilder sb = new StringBuilder();
            try {
                String password = DigestUtils.md5DigestAsHex((sb.append(salt).append(ro.getPassword())).toString().getBytes());
                newuser.setPassword(password);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            newuser.setPerfession(ro.getPerfession());
            newuser.setIdCard(ro.getIdCard());
            newuser.setPhone(ro.getPhone());
            newuser.setUserType(ro.getUserType());
            newuser.setUsername(ro.getUsername());
            //
            newuser.setDate(ro.getDate());
            newuser.setEmail(ro.getEmail());
            newuser.setSex(ro.getSex());
            newuser.setAddress(ro.getAddress());
            //新增用户
            userDao.insert(newuser);
        }
        //跳转视图
        modelAndView.setViewName("redirect:/admin/user/page");
        return modelAndView;
    }

    @RequestMapping("/user/shenhe")
    public String shenhe(Integer id){
        Users users = userDao.selectById(id);
        users.setIndex(1);
        userDao.updateById(users);
        return "redirect:/admin/user/page";
    }

    //删除用户
    @RequestMapping("/user/delete")
    public ModelAndView update(int id){
        ModelAndView modelAndView = new ModelAndView();
        LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<>();
        //搜索用户id是否符合条件
        wrapper.eq(Users::getId, id);
        //查找用户存在
        Users users = userDao.selectOne(wrapper);
        if(users == null){
            throw new RuntimeException("用户不存在");
        }
        //删除数据库记录
        userDao.deleteById(users);
        //重定向视图
        modelAndView.setViewName("redirect:/admin/user/page");
        return modelAndView;
    }

    @RequestMapping("/active/add.html")
    public ModelAndView acajshd(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/admin/active/detail");
        List<Huodongleixin> Huodongleixins = typeDao.selectList(null);
        modelAndView.addObject("types", Huodongleixins);
        return modelAndView;
    }

    @Autowired
    private ActiveDao activeDao;

    @RequestMapping("/active/page")
    public ModelAndView activePage(PageRO<Huodongxinxi> ro){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/admin/active/list");
        //查找是否请求参数中有搜索值
        //分页查询用户
        if(StringUtils.isEmpty(ro.getName())){
            ro.setName(null);
        }
        Page<Huodongxinxi> activePage = activeDao.selectPageBySearch(ro);
        activePage.getRecords().forEach(a->{
            Users users = userDao.selectById(a.getUid());
            a.setUser(users);
            Huodongleixin huodongleixin = typeDao.selectById(a.getTid());
            a.setType(huodongleixin);
        });
        List<Huodongleixin> Huodongleixins = typeDao.selectList(null);
        modelAndView.addObject("types", Huodongleixins);
        //将结果注入页面返回
        modelAndView.addObject("page", activePage);
        return modelAndView;
    }

    @RequestMapping("/active/update")
    public ModelAndView activeUpdate(Huodongxinxi huodongxinxi){
        if(hostHolder.getUser().getUserType() == 0){
            Integer uid = hostHolder.getUser().getId();

            if(Objects.nonNull(huodongxinxi.getId())){
                Huodongxinxi a = activeDao.selectById(huodongxinxi.getId());
                a.setName(huodongxinxi.getName());
                a.setAddress(huodongxinxi.getAddress());
                a.setTime(huodongxinxi.getTime());
                a.setContent(huodongxinxi.getContent());
                a.setUid(uid);
                activeDao.updateById(a);
            }else{
                huodongxinxi.setUid(uid);
                activeDao.insert(huodongxinxi);
            }
            ModelAndView mav = new ModelAndView();
            mav.setViewName("redirect:/admin/active/page");
            return mav;
        }else{
            Integer uid = hostHolder.getUser().getId();
            Integer aid = huodongxinxi.getId();
            String comment = huodongxinxi.getComment();
            Huoodngbaoming huoodngbaoming = new Huoodngbaoming();
            huoodngbaoming.setAid(aid);
            huoodngbaoming.setUid(uid);
            huoodngbaoming.setComment(comment);
            huoodngbaoming.setTime(new Date());
            huoodngbaoming.setStatus("审核中(已报名)");
            huoodngbaoming.setIndex(0);
            applicationDao.insert(huoodngbaoming);
            ModelAndView mav = new ModelAndView();
            mav.setViewName("redirect:/admin/active/page");
            return mav;
        }
    }

    //类型新增的接口
    @RequestMapping("/type/add.html")
    public ModelAndView typeaddhtml(){
        ModelAndView modelAndView = new ModelAndView();
        //跳转新增类型的页面
        modelAndView.setViewName("/admin/type/detail");
        return modelAndView;
    }

    //分页类型
    @RequestMapping("/type/page")
    public ModelAndView typepage(PageRO<Huodongleixin> ro){
        ModelAndView modelAndView = new ModelAndView();
        //跳转类型列表的界面
        modelAndView.setViewName("/admin/type/list");
        LambdaQueryWrapper<Huodongleixin> wrapper = new LambdaQueryWrapper<>();
        //查找请求是否需要模糊1
        if(StringUtils.isNotEmpty(ro.getSearch())){
            wrapper.like(Huodongleixin::getName, ro.getSearch());
        }
        //查找分页的数据
        PageRO<Huodongleixin> page = typeDao.selectPage(ro, wrapper);
        //将数据注入视图
        modelAndView.addObject("page", page);
        modelAndView.addObject("msg", ro.getMsg());

        return modelAndView;
    }



    //新增/更新的类型
    @RequestMapping("/type/update")
    public ModelAndView typeupdate(Huodongleixin huodongleixin){
        ModelAndView modelAndView = new ModelAndView();
        //分页的类型
        modelAndView.setViewName("redirect:/admin/type/page");
        //类型id是否存在
        if(Objects.nonNull(huodongleixin.getId())){
            LambdaQueryWrapper<Huodongleixin> w = new LambdaQueryWrapper<>();
            //查找类型是否有对应的id
            w.eq(Huodongleixin::getId, huodongleixin.getId());
            //查找当前的类型
            Huodongleixin currentHuodongleixin = typeDao.selectOne(w);
            currentHuodongleixin.setName(huodongleixin.getName());
            //更新类型
            typeDao.updateById(currentHuodongleixin);
        }else{
            //新增类型
            LambdaQueryWrapper<Huodongleixin> w = new LambdaQueryWrapper<>();
            //查找是否有重复的类型名称
            w.eq(Huodongleixin::getName, huodongleixin.getName());
            Huodongleixin huodongleixin1 = typeDao.selectOne(w);
            if(huodongleixin1 != null){
                modelAndView.addObject("msg", "类别已经存在");
                return modelAndView;
            }
            Huodongleixin huodongleixin2 = new Huodongleixin();
            huodongleixin2.setName(huodongleixin.getName());
            //将填写的数据注入新增到数据库中
            typeDao.insert(huodongleixin2);
        }
        return modelAndView;
    }


    //类型详情
    @RequestMapping("/type/detail")
    public ModelAndView typedetail(String id){
        ModelAndView modelAndView = new ModelAndView();
        LambdaQueryWrapper<Huodongleixin> wrapper = new LambdaQueryWrapper<>();
        //是否类型有相同的id
        wrapper.eq(Huodongleixin::getId, id);
        Huodongleixin huodongleixin = typeDao.selectOne(wrapper);
        if(huodongleixin == null){
            throw new RuntimeException("用户不存在");
        }
        //跳转到类型的详情的页面
        modelAndView.setViewName("/admin/type/detail");
        //将数据注入视图
        modelAndView.addObject("type", huodongleixin);
        return modelAndView;
    }

    @RequestMapping("/type/delete")
    public ModelAndView delete(Integer id){
        LambdaQueryWrapper<Huodongxinxi> huodongxinxiLambdaQueryWrapper = new LambdaQueryWrapper<>();
        huodongxinxiLambdaQueryWrapper.eq(Huodongxinxi::getTid, id);
        List<Huodongxinxi> huodongxinxis = activeDao.selectList(huodongxinxiLambdaQueryWrapper);
        if(!CollectionUtils.isEmpty(huodongxinxis)){
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("redirect:/admin/type/page?msg=typecannotdel");
            return modelAndView;
        }
        Huodongleixin huodongleixin = typeDao.selectById(id);
        typeDao.deleteById(huodongleixin);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("redirect:/admin/type/page");
        return modelAndView;
    }

    @RequestMapping("/active/detail")
    public ModelAndView activeDetail(Integer id){
        ModelAndView modelAndView = new ModelAndView();
        Huodongxinxi huodongxinxi = activeDao.selectById(id);
        Users users = userDao.selectById(huodongxinxi.getUid());
        huodongxinxi.setUser(users);
        modelAndView.addObject("active", huodongxinxi);
        modelAndView.setViewName("/admin/active/detail");
        List<Huodongleixin> Huodongleixins = typeDao.selectList(null);
        modelAndView.addObject("types", Huodongleixins);

        LambdaQueryWrapper<Huoodngbaoming> applicationLambdaQueryWrapper = new LambdaQueryWrapper<>();
        applicationLambdaQueryWrapper.eq(Huoodngbaoming::getUid, hostHolder.getUser().getId());
        applicationLambdaQueryWrapper.eq(Huoodngbaoming::getAid, id);
        applicationLambdaQueryWrapper.eq(Huoodngbaoming::getIndex, 0);
        Huoodngbaoming huoodngbaoming = applicationDao.selectOne(applicationLambdaQueryWrapper);
        if(Objects.nonNull(huoodngbaoming)){
            modelAndView.addObject("app", huoodngbaoming);
        }

        return modelAndView;
    }

    @RequestMapping("/app/page")
    public ModelAndView appPage(PageRO<Huoodngbaoming> ro){
        if(StringUtils.isEmpty(ro.getName())){
            ro.setName(null);
        }
        if(StringUtils.isEmpty(ro.getUsername())){
            ro.setUsername(null);
        }
        Page<Huoodngbaoming> applicationPage = applicationDao.selectPageBySearch(ro);
        applicationPage.getRecords().forEach(a->{
            Users users = userDao.selectById(a.getUid());
            a.setUser(users);
            Huodongxinxi huodongxinxi = activeDao.selectById(a.getAid());
            Users users1 = userDao.selectById(huodongxinxi.getUid());
            Huodongleixin huodongleixin = typeDao.selectById(huodongxinxi.getTid());
            huodongxinxi.setType(huodongleixin);
            huodongxinxi.setUser(users1);
            a.setActive(huodongxinxi);
        });
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/admin/app/list");
        modelAndView.addObject("page", applicationPage);
        return modelAndView;
    }

    @GetMapping("/application/detail")
    public ModelAndView appDetail(@RequestParam("id") Integer id){
        ModelAndView modelAndView = new ModelAndView();
        Huoodngbaoming huoodngbaoming = applicationDao.selectById(id);
        Integer aid = huoodngbaoming.getAid();
        Huodongxinxi huodongxinxi = activeDao.selectById(aid);
        huodongxinxi.setUser(userDao.selectById(huodongxinxi.getUid()));
        huodongxinxi.setType(typeDao.selectById(huodongxinxi.getTid()));
        Integer uid = huoodngbaoming.getUid();
        Users users = userDao.selectById(uid);
        huoodngbaoming.setUser(users);
        huoodngbaoming.setActive(huodongxinxi);
        modelAndView.setViewName("/admin/app/detail");
        modelAndView.addObject("app", huoodngbaoming);
        return modelAndView;
    }

    @RequestMapping("/application/reply/success")
    public ModelAndView applicationReplySuccess(Huoodngbaoming huoodngbaoming){

        Huoodngbaoming old = applicationDao.selectById(huoodngbaoming.getId());
        old.setReply(huoodngbaoming.getReply());
        old.setStatus("报名成功(已同意)");
        old.setIndex(1);
        applicationDao.updateById(old);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("redirect:/admin/app/page");
        return modelAndView;

    }

    @RequestMapping("/application/reply/fail")
    public ModelAndView applicationReplyFail(Huoodngbaoming huoodngbaoming){

        Huoodngbaoming old = applicationDao.selectById(huoodngbaoming.getId());
        old.setReply(huoodngbaoming.getReply());
        old.setStatus("报名失败(已驳回)");
        old.setIndex(2);
        applicationDao.updateById(old);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("redirect:/admin/app/page");
        return modelAndView;

    }

    @RequestMapping("/active/my/page")
    public ModelAndView activeMy(PageRO<Huoodngbaoming> ro){
        if(StringUtils.isEmpty(ro.getName())){
            ro.setName(null);
        }
        if(StringUtils.isEmpty(ro.getUsername())){
            ro.setUsername(null);
        }
        Integer uid = hostHolder.getUser().getId();
        LambdaQueryWrapper<Huoodngbaoming> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Huoodngbaoming::getUid, uid);
        ro.setUid(uid);
        Page<Huoodngbaoming> applicationPage = applicationDao.selectPageBySearchAndUid(ro);
        applicationPage.getRecords().forEach(app->{
            Huodongxinxi huodongxinxi = activeDao.selectById(app.getAid());
            huodongxinxi.setUser(userDao.selectById(huodongxinxi.getUid()));
            huodongxinxi.setType(typeDao.selectById(huodongxinxi.getTid()));
            app.setActive(huodongxinxi);
            app.setUser(userDao.selectById(app.getUid()));
        });

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/admin/my/active/list");
        modelAndView.addObject("page", applicationPage);
        return modelAndView;
    }

    @RequestMapping("/active/my/detail")
    public ModelAndView activeMyDetail(Integer id){
        ModelAndView modelAndView = new ModelAndView();
        Huoodngbaoming huoodngbaoming = applicationDao.selectById(id);
        Integer aid = huoodngbaoming.getAid();
        Huodongxinxi huodongxinxi = activeDao.selectById(aid);
        huodongxinxi.setUser(userDao.selectById(huodongxinxi.getUid()));
        huodongxinxi.setType(typeDao.selectById(huodongxinxi.getTid()));
        Integer uid = huoodngbaoming.getUid();
        Users users = userDao.selectById(uid);
        huoodngbaoming.setUser(users);
        huoodngbaoming.setActive(huodongxinxi);
        modelAndView.setViewName("/admin/my/active/detail");
        modelAndView.addObject("app", huoodngbaoming);
        return modelAndView;
    }

    @Autowired
    private MsgDao msgDao;


    @RequestMapping("/msg/add.html")
    public ModelAndView msgAddHtml(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/admin/msg/detail");
        List<Huodongxinxi> Huodongxinxis = activeDao.selectList(null);
        List<Users> usersList = userDao.selectList(null);
        modelAndView.addObject("actives", Huodongxinxis);
        modelAndView.addObject("users", usersList);
        return modelAndView;
    }

    @RequestMapping("/msg/page")
    public ModelAndView msgPage(PageRO<Huodongtongzhi> ro){
        Page<Huodongtongzhi> msgPage = msgDao.selectMsgByName(ro);
        msgPage.getRecords().forEach(mp->{
            Huodongxinxi huodongxinxi = activeDao.selectById(mp.getAid());
            huodongxinxi.setUser(userDao.selectById(huodongxinxi.getUid()));
            huodongxinxi.setType(typeDao.selectById(huodongxinxi.getTid()));
            mp.setActive(huodongxinxi);
            mp.setUser(userDao.selectById(mp.getUid()));
        });
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("page", msgPage);
        modelAndView.setViewName("/admin/msg/list");
        return modelAndView;

    }

    @RequestMapping("/msg/detail")
    public ModelAndView msgdetail(Integer id){
        Huodongtongzhi huodongtongzhi = msgDao.selectById(id);
        huodongtongzhi.setActive(activeDao.selectById(huodongtongzhi.getAid()));
        huodongtongzhi.setUser(userDao.selectById(huodongtongzhi.getUid()));
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/admin/msg/detail");
        modelAndView.addObject("msg", huodongtongzhi);
        List<Users> usersList = userDao.selectList(null);
        List<Huodongxinxi> Huodongxinxis = activeDao.selectList(null);
        modelAndView.addObject("actives", Huodongxinxis);
        modelAndView.addObject("users", usersList);
        return modelAndView;
    }

    @RequestMapping("/msg/update")
    public ModelAndView msgUpdate(Huodongtongzhi huodongtongzhi){

        if(Objects.isNull(huodongtongzhi.getId())){
            huodongtongzhi.setTime(new Date());
            msgDao.insert(huodongtongzhi);
        }else{
            msgDao.updateById(huodongtongzhi);
        }

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("redirect:/admin/msg/list");
        return modelAndView;
    }

    @RequestMapping("/msg/delete")
    public ModelAndView msgDelete(Integer id){

        Huodongtongzhi huodongtongzhi = msgDao.selectById(id);

        msgDao.deleteById(huodongtongzhi);

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("redirect:/admin/msg/list");
        return modelAndView;
    }


    @RequestMapping("/msg/my/page")
    public ModelAndView msgmyPage(PageRO<Huodongtongzhi> ro){
        Integer id = hostHolder.getUser().getId();
        ro.setUid(id);
        Page<Huodongtongzhi> msgPage = msgDao.selectMsgByNameAndUid(ro);
        msgPage.getRecords().forEach(mp->{
            Huodongxinxi huodongxinxi = activeDao.selectById(mp.getAid());
            huodongxinxi.setUser(userDao.selectById(huodongxinxi.getUid()));
            huodongxinxi.setType(typeDao.selectById(huodongxinxi.getTid()));
            mp.setActive(huodongxinxi);
            mp.setUser(userDao.selectById(mp.getUid()));
        });
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("page", msgPage);
        modelAndView.setViewName("/admin/my/msg/list");
        return modelAndView;

    }

    @RequestMapping("/msg/my/detail")
    public ModelAndView msgmydetail(Integer id){
        Huodongtongzhi huodongtongzhi = msgDao.selectById(id);
        huodongtongzhi.setActive(activeDao.selectById(huodongtongzhi.getAid()));
        huodongtongzhi.setUser(userDao.selectById(huodongtongzhi.getUid()));
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/admin/my/msg/detail");
        modelAndView.addObject("msg", huodongtongzhi);
        List<Users> usersList = userDao.selectList(null);
        List<Huodongxinxi> Huodongxinxis = activeDao.selectList(null);
        modelAndView.addObject("actives", Huodongxinxis);
        modelAndView.addObject("users", usersList);
        return modelAndView;
    }

    @Autowired
    private ConfigDao configDao;

    @RequestMapping("/config/page")
    public ModelAndView configPage(PageRO<Config> ro){
        LambdaQueryWrapper<Config> configLambdaQueryWrapper = new LambdaQueryWrapper<>();
        configLambdaQueryWrapper.orderBy(true, false, Config::getDate);
        PageRO<Config> configPageRO = configDao.selectPage(ro, configLambdaQueryWrapper);
        ModelAndView modelAndView = new ModelAndView();
        configPageRO.getRecords().forEach(c->{
            c.setUser(userDao.selectById(c.getUid()));
        });
        modelAndView.addObject("page", configPageRO);
        modelAndView.setViewName("/admin/index");
        return modelAndView;
    }


}
